import { Router } from "vue-router";
import { useAuthStore, usePermissionStore, useUserStore } from "@/store";
import { getUserInfo } from "@/api/user.ts";
import * as permissions from "../permissions";

const WHITE_LIST = ["/login", "/404", "/autoLogin"];

function hideLoading() {
  const loadingEl = document.getElementById("loading-container");
  if (loadingEl) {
    loadingEl!.className = "loading-container hide";
    setTimeout(() => {
      loadingEl!.style["display"] = "none";
    }, 1000);
  }
}

export function createPermissionGuard(router: Router): void {
  router.beforeEach(async (to) => {
    const authStore = useAuthStore();
    const token = authStore.accessToken;

    if (!token) {
      hideLoading();

      if (WHITE_LIST.indexOf(to.path) > -1) return true;
      return { path: "login", query: { ...to.query, redirect: to.path } };
    }

    if (to.path === "/login") return { path: "/" };
    if (WHITE_LIST.includes(to.path)) return true;
    const userStore = useUserStore();
    const permissionStore = usePermissionStore();
    if (!userStore.userInfo.id) {
      try {
        const [user] = await Promise.all([getUserInfo()]);
        // userStore.setDicts(dicts.data);
        userStore.setUser(user.data);
        permissionStore.setPermissions(
          permissions[
            user.data.role.name.toLocaleLowerCase() as keyof typeof permissions
          ],
        );

        // permissionStore.setPermissions(permission.data)

        hideLoading();

        const routeComponents = import.meta.glob("@/views/**/*.vue");
        permissionStore.accessRoutes.forEach((route) => {
          route.component =
            routeComponents[route.component as any] || undefined;
          !router.hasRoute(route.name!) && router.addRoute(route);
        });

        return { ...to, replace: true };
      } catch (err: any) {
        return authStore.logout();
      }
    }

    const routes = router.getRoutes();

    const route = routes.find((route) => route.name == to.name);
    if (route) {
      if (route.meta.admin) {
        return userStore.userInfo.admin ? true : { name: "403" };
      } else {
        return true;
      }
    }
    if (to.path == "/" && !permissionStore.validateMenuPath(to.path)) {
      const route = permissionStore.getValidRoute;
      return { ...route, replace: true };
    }

    return {
      name: "404",
    };
    // 判断是无权限还是404
  });
}
